<template>
  <el-container style="height: 100vh;">
    <!-- 左侧导航栏 -->
    <el-aside :width="sideWidth + 'px'" style="background-color: rgb(238, 241, 246)">
      <Sidebar />
    </el-aside>

    <!-- 右侧内容 -->
    <el-container>
      <!-- 页面头部 -->
      <el-header style="background-color: #409EFF; padding: 10px; color: white">
        <div style="display: flex; align-items: center">
          <!-- 头像 -->
          <el-avatar
              size="60"
              src="#"
              alt="头像"
              style="margin-right: 20px"
          />
          <!-- 用户信息 -->
          <div>
            <h2 style="margin: 0; font-size: 24px">熊老师</h2>
            <p style="margin: 0; font-size: 16px">大数据老师</p>
          </div>
        </div>
      </el-header>

      <!-- 页面主体 -->
      <el-main style="padding: 20px">
        <!-- 搜索区域 -->
        <div style="margin-bottom: 20px;">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input
                  v-model="search.name"
                  placeholder="请输入作业名称"
                  clearable
              />
            </el-col>
            <el-col :span="8">
              <el-select
                  v-model="search.status"
                  placeholder="请选择当前状态"
                  clearable
              >
                <el-option label="未开始" value="未开始" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已结束" value="已结束" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select
                  v-model="search.class_number"
                  placeholder="请选择布置班级"
                  clearable
              >
                <el-option label="81" value="81" />
                <el-option label="82" value="82" />
                <el-option label="83" value="83" />
                <el-option label="84" value="84" />
              </el-select>
            </el-col>
          </el-row>
        </div>

        <el-card shadow="always" style="margin-top: 30px;">
          <el-table
              :data="filteredHomeworkList"
              style="width: 100%"
              border
              row-key="id"
          >
            <!-- 修改列标题为“作业名称” -->
            <el-table-column
                prop="name"
                label="作业名称"
                width="250"
                align="center"
            />
            <!-- 当前状态 -->
            <el-table-column
                label="当前状态"
                width="250"
                align="center"
            >
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row)" class="status-tag">
                  {{ getStatusText(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <!-- 布置给的班级 -->
            <el-table-column
                label="布置给的班级"
                width="250"
                align="center"
            >
              <template #default="scope">
                <el-tag :type="getSubmitTagType(scope.row.class_number)" class="status-tag">
                  {{ scope.row.class_number }}班
                </el-tag>
              </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column
                label="操作"
                align="center"
            >
              <template #default="scope">
                <div class="action-buttons">
                  <!-- 查看完成情况 -->
                  <el-button
                      :disabled="!isFinished(scope.row)"
                      type="text"
                      class="action-button view-completion-button"
                      @click="viewCompletionStatus(scope.row)"
                  >
                    查看完成情况
                  </el-button>
                  <!--                  查看分析报告-->
                  <el-button
                      :disabled="!isFinished(scope.row)"
                      type="text"
                      class="action-button view-report-button"
                      @click="viewAnalysisReport(scope.row)"
                  >
                    查看分析报告
                  </el-button>
                  <!-- 删除 -->
                  <el-button
                      :disabled="!isBeforeStartTime(scope.row)"
                      type="text"
                      class="action-button delete-button"
                      @click="deleteHomework(scope.row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!-- 分页组件 -->
        <el-pagination
            v-model:currentPage="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { ElMessage, ElMessageBox } from "element-plus";
import Sidebar from "@/views/SidebarForT.vue";
import axios from "axios";

export default {
  components: {
    Sidebar,
  },
  mounted() {
    this.getHomeworkList();
  },
  data() {
    return {
      sideWidth: 200, // 侧边栏宽度
      HomeworkList: [],
      search: {
        name: "",
        status: "",
        class_number: "",
      },
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示条数
      total: 0, // 总条数
    };
  },
  computed: {
    filteredHomeworkList() {
      let result = this.HomeworkList.filter(item => item.isUse === 'y');

      if (this.search.name) {
        result = result.filter(item => item.name.includes(this.search.name));
      }
      if (this.search.status) {
        result = result.filter(item => this.getStatusText(item) === this.search.status);
      }
      if (this.search.class_number) {
        result = result.filter(item => item.class_number === this.search.class_number);
      }

      return result.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    }
  },
  methods: {
    handleSizeChange(newSize) {
      this.pageSize = newSize; // 更新每页显示条数
      this.currentPage = 1; // 重置当前页码为第一页
    },
    getHomeworkList() {
      axios.get("http://localhost:80/teachers/getAssignmentsList").then((resp) => {
        const result = resp.data;
        this.HomeworkList = result.data.map(item => ({
          ...item,
          status: this.getStatusText(item),
          submitted: this.getSubmitText(item.isSubmit)
        }));
        this.total = this.HomeworkList.length; // 更新总条数
      });
    },
    getStatusTagType(row) {
      switch (this.getStatusText(row)) {
        case "未开始":
          return "info";
        case "进行中":
          return "warning";
        case "已结束":
          return "success";
        default:
          return "";
      }
    },
    getSubmitTagType(submitted) {
      return submitted === "y" ? "success" : "danger";
    },
    getStatusText(row) {
      const now = new Date();
      const startTime = new Date(row.start_time);
      const endTime = new Date(row.end_time);

      if (now > endTime) {
        return "已结束";
      } else if (now >= startTime && now <= endTime) {
        return "进行中";
      } else {
        return "未开始";
      }
    },
    getSubmitText(isSubmit) {
      return isSubmit === "y" ? "已提交" : "未提交";
    },
    isFinished(row) {
      const now = new Date();
      const endTime = new Date(row.end_time);
      return now > endTime;
    },
    isBeforeStartTime(row) {
      const now = new Date();
      const startTime = new Date(row.start_time);
      return now < startTime;
    },
    viewCompletionStatus(row) {
      console.log(row.name);
      this.$router.push({
        name: 'HomeworkStatus',
        query: {
          name: row.name, // 传递作业名称
          class_number: row.class_number // 传递班级编号
        }
      });
    },
    viewAnalysisReport(row) {
      console.log(row.name); // 打印作业名称，用于调试
      this.$router.push({
        name: 'AnalysisReport',
        query: {
          name: row.name, // 传递作业名称
          class_number: row.class_number // 传递班级编号
        }
      });
    },
    deleteHomework(row) {
      ElMessageBox.confirm(`确定要删除作业 "${row.name}" 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            // 调用后端删除接口，使用 GET 方法
            axios.get("http://localhost:80/assignments/Tdelete", {
              params: {
                class_number: row.class_number,
                name: row.name
              }
            })
                .then((response) => {
                  if (response.data.code === 0) {
                    // 删除成功，更新本地数据
                    this.getHomeworkList();
                    ElMessage.success("删除成功");
                  } else {
                    ElMessage.error(response.data.message || "删除失败");
                  }
                })
                .catch((error) => {
                  console.error("删除请求失败:", error);
                  if (error.response) {
                    ElMessage.error(error.response.data.message || "删除请求失败");
                  } else {
                    ElMessage.error("删除请求失败，请检查网络或联系管理员");
                  }
                });
          })
          .catch(() => {
            ElMessage.info("已取消删除");
          });
    },
    handlePageChange(newPage) {
      this.currentPage = newPage;
    }
  }
};
</script>

<style scoped>
/* 表格整体样式 */
.Homework-table {
  width: 100%;
}

/* 表头和内容对齐 */
.el-table th {
  text-align: center !important;
  background-color: #f5f7fa;
  font-size: 16px;
  padding: 12px 0;
}

.el-table td {
  text-align: center !important;
  font-size: 16px;
  padding: 12px 0;
}

/* 操作按钮样式 */
.action-button {
  font-size: 16px !important;
  padding: 8px 16px !important;
  margin: 0 8px !important;
  cursor: pointer;
}

.action-button:disabled {
  background-color: #c0c4cc !important;
  color: #fff !important;
  cursor: not-allowed;
}

.delete-button {
  background-color: #ff4d4f !important;
  color: #fff !important;
}

/* 状态标签样式 */
.status-tag {
  font-size: 16px !important;
  padding: 8px 16px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}

/* 确保按钮之间的间距 */
.el-button + .el-button {
  margin-left: 10px;
}

/* 确保标签居中显示 */
.el-tag {
  display: inline-block;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
